package com.study.spmongodb.wwj.thread2.char06;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/7 22:41
 */
public class ReadWriteLock {

    private int readingReaders = 0;

    private int waitingReaders = 0;

    private int writingWriters = 0;

    private int waitingWriters = 0;

    public synchronized void readLock() {
        this.waitingReaders++;
        try {
            while (writingWriters > 0) {
                this.notify();
            }
            this.readingReaders++;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.waitingReaders--;
        }
    }

    public synchronized void readUnlock() {
        this.readingReaders--;
        this.notifyAll();
    }

    public synchronized void writeLock() {
        this.waitingWriters++;
        try {
            while (readingReaders > 0 || writingWriters > 0) {
                this.wait();
            }
            this.writingWriters++;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.waitingWriters--;
        }
    }

    public synchronized void writeUnlock() {
        this.writingWriters--;
        this.notifyAll();
    }


}
